package main

import (
	"fmt"
	"math/rand"
	"net"
	"time"

	"github.com/sony/sonyflake"
	"go.uber.org/zap"
)

var sf *sonyflake.Sonyflake

func init() {
	sf = sonyflake.NewSonyflake(sonyflake.Settings{})
	if sf == nil {
		panic("sonyflake not created")
	}
}

func GetRandomString(l int) string {
	str := "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
	bytes := []byte(str)
	result := []byte{}
	r := rand.New(rand.NewSource(time.Now().UnixNano()))
	for i := 0; i < l; i++ {
		result = append(result, bytes[r.Intn(len(bytes))])
	}
	return string(result)
}

func GetLocalDomainNoUseTcpPort(startPort int, maxPort int) int {
	currentPort := 0
	for port := startPort; port < maxPort; port++ {
		address := fmt.Sprintf("%s:%d", "0.0.0.0", port)
		listener, err := net.Listen("tcp", address)
		if err == nil {
			// 端口可用
			defer listener.Close()
			fmt.Printf("端口 %d 可用\n", port)
			currentPort = port
			break
		}
	}
	return currentPort
}

func GenerateMessageId(logger *zap.SugaredLogger) (uint64, uint64) {

	id, err := sf.NextID()

	if err != nil {
		logger.Error(err.Error(), "GenerateMessageId Error")

		return 0, 0
	}

	// 获取当前时间
	now := time.Now()

	// 获取纳秒级时间戳
	timestamp := now.UnixNano()

	return uint64(id), uint64(timestamp)
}
